import { getSw8, getTimestamp, InterceptFetchType } from "@/core";
const { fetch: originFetch } = globalThis;

// 拦截fetch
const interceptFetch = ({ appId, pagePath, onError, onBefore, onAfter }: InterceptFetchType) => {
  function newFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
  async function newFetch(...args: any) {
    let [url, options] = args;
    const startTime = getTimestamp();
    let res: Response | undefined;
    if (args[0] instanceof Request) {
      url = new URL(url.url);
    } else {
      if (/^https?:\/\//.test(args[0])) {
        url = new URL(args[0]);
      } else if (args[0].startsWith("//")) {
        url = new URL(`${globalThis.location.protocol}${args[0]}`);
      } else {
        url = new URL(globalThis.location.href);
        url.pathname = args[0];
      }
    }
    if (!options) {
      options = {};
    }
    if (!options.headers) {
      options.headers = {};
    }
    options.headers["sw8"] = getSw8({
      appId: appId,
      herf: url.href,
      pagePath,
    });

    try {
      onBefore && onBefore({ url, method: options.method, options });
      res = await originFetch(url, options);
      onAfter && onAfter(res);
    } catch (err) {}
    if (!res) return;
    if (!(res.ok && res.status >= 200 && res.status < 300)) {
      onError({
        url,
        status: res.status,
        statusText: res.statusText,
        method: options.method,
        body: options.body,
        elapsedTime: getTimestamp() - startTime,
      });
    }

    return res;
  }
  return newFetch;
};

export { interceptFetch };
